import React, { useState, useEffect } from "react";
import { Link, useParams, useHistory } from "react-router-dom";
import "./editGoods.scss";
import axios from "axios";
import { BaseUrl } from "../manger/network";
import tokenManager from "../manger/tokenManager";
import { post } from "../manger/network";
import {
  Layout,
  Menu,
  Button,
  Input,
  Form,
  Upload,
  message,
  Pagination,
  List,
  Image,
  Card,
} from "antd";
import "antd/dist/antd.css";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
const { Header, Content, Footer, Sider } = Layout;

const FormItem = Form.Item;

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

async function getBase64WithUrl(imgUrl, callback) {
  window.URL = window.URL || window.webkitURL;
  var xhr = new XMLHttpRequest();
  xhr.open("get", imgUrl, true);
  // 至关重要
  xhr.responseType = "blob";
  xhr.onload = function () {
    if (this.status == 200) {
      //得到一个blob对象
      var blob = this.response;
      // 至关重要
      getBase64(blob, (data) => {
        callback(data);
      });
    }
  };
  xhr.send();
}

function beforeUpload(file) {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG/PNG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJpgOrPng && isLt2M;
}

export default function EditGoods() {
  const params = useParams();
  const history = useHistory();
  const [imageUrl, setImageUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [realUrl, setRealUrl] = useState(null);
  const [goodsId, setGoodsId] = useState("");

  const [goodsName, setGoodsName] = useState("");
  const [goodsDesc, setGoodsDesc] = useState("");
  const [goodsPrice, setGoodsPrice] = useState("");
  const [goodsCount, setGoodsCount] = useState(1);

  useEffect(async () => {
    console.log(history.location.state);
    let data = history.location.state;
    setRealUrl(data.image);
    setGoodsId(data.id);
    setGoodsName(data.name);
    setGoodsCount(data.count);
    setGoodsPrice(data.price);
    setGoodsDesc(data.description);
    getBase64WithUrl(`${BaseUrl}/${data.image}`, (base64) => {
      setImageUrl(base64);
    });
  }, []);

  return (
    <div className="container">
      <Content style={{ margin: "0 16px" }}>
        <div className="siteView" style={{ padding: 24, minHeight: 360 }}>
          <div className="whiteView">
            <Form className="form">
              <FormItem label="商品名称:" className="formitem">
                <Input
                  placeholder="请输入商品名称"
                  value={goodsName}
                  onChange={(e) => {
                    setGoodsName(e.target.value);
                  }}
                  maxLength={20}
                />
              </FormItem>
              <FormItem label="商品描述:" className="formitem">
                <Input
                  value={goodsDesc}
                  placeholder="请输入商品描述"
                  onChange={(e) => {
                    setGoodsDesc(e.target.value);
                  }}
                  maxLength={50}
                />
              </FormItem>
              <FormItem label="商品价格:" className="formitem">
                <Input
                  value={goodsPrice}
                  placeholder="请输入商品价格"
                  onChange={(e) => {
                    setGoodsPrice(e.target.value);
                  }}
                  maxLength={8}
                />
              </FormItem>
              <FormItem label="商品数量:" className="formitem">
                <Input
                  value={goodsCount}
                  placeholder="请输入商品数量"
                  onChange={(e) => {
                    setGoodsCount(e.target.value);
                  }}
                  maxLength={6}
                />
              </FormItem>
              <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={`${BaseUrl}/upload`}
                beforeUpload={beforeUpload}
                onChange={(info) => {
                  if (info.file.status === "uploading") {
                    setLoading(true);
                    return;
                  }
                  if (info.file.status === "done") {
                    getBase64(info.file.originFileObj, (imageUrl) => {
                      setLoading(false);
                      setImageUrl(imageUrl);
                      setRealUrl(info.file.response.url);
                    });
                  }
                }}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
                ) : (
                  <div>
                    {loading ? <LoadingOutlined /> : <PlusOutlined />}
                    <div style={{ marginTop: 8 }}>上传图片</div>
                  </div>
                )}
              </Upload>
              <Button
                type="primary"
                className="confirmBtn"
                onClick={() => {
                  if (goodsName.length == 0) {
                    message.error("请输入商品名称");
                    return;
                  }
                  if (goodsPrice.length == 0) {
                    message.error("请输入商品价格");
                    return;
                  }
                  if (!/^\d+$/.test(goodsCount)) {
                    message.error("请输入正确的商品数量");
                    return;
                  }
                  post("/updategoods", {
                    id: goodsId,
                    name: goodsName,
                    desc: goodsDesc,
                    price: goodsPrice,
                    url: realUrl,
                    count: goodsCount,
                  })
                    .then((response) => {
                      if (response.code == 0) {
                        message.success("修改商品成功");
                      } else {
                        message.error(response.msg);
                      }
                    })
                    .catch((err) => {
                      message.error(err.message);
                      console.log(err);
                    });
                }}
              >
                确认
              </Button>
            </Form>
          </div>
        </div>
      </Content>
    </div>
  );
}
